/**
 * Created by admin on 2018/11/16.
 */
const Koa = require('koa');

const app = new Koa();
const onError = require('koa-onerror');
const bodyParser = require('koa-bodyparser');
const responseFormat = require('./middleware/response_format');
const requestFormat = require('./middleware/request_format');
const scoreInfoRt = require('./routes/scoreInfoRoute');
const tongdunRt = require('./routes/tongdunRoute');
const logUtil = require('./utils/log_util');
const serve = require('koa-static');

// error handler
onError(app);

// middlewares
app.use(bodyParser({
  enableTypes: ['json', 'form', 'text'],
  formLimit: '5mb',
  jsonLimit: '5mb',
  textLimit: '5mb'
}));

// app.use(json());
// app.use(logger());
app.use(serve(`${__dirname}/../public`));



// logger
app.use(async (ctx, next) => {
  // ignore the favicon.ico
  if (ctx.path === '/favicon.ico') {
    return;
  }
  const start = new Date();
  try {
    await next();
    const ms = new Date() - start;
    logUtil.info(`${ctx.method} ${ctx.url} - ${ms}ms`);
  } catch (error) {
    logUtil.error(`${ctx.method} ${ctx.url} exception: `, error);
    if (error) {
      ctx.body = {
        status: -1,
        msg: error
      };
    } else {
      ctx.body = {
        status: -1,
        msg: 'Server Exception'
      };
    }
  }
});

// response format
app.use(responseFormat());
app.use(requestFormat());
// routes
app.use(scoreInfoRt.routes());
app.use(tongdunRt.routes());

// response
app.on('error', (err, ctx) => {
  logUtil.error(`${ctx.method} ${ctx.url} error event: `, err);
  ctx.body = {
    status: -1,
    msg: 'Server Exception'
  };
});

module.exports = app;

